/* eslint-disable prefer-destructuring */
const path = require('path')
// const fs = require('fs');
const TerserPlugin = require('terser-webpack-plugin')
// const pkg = require('../package.json')
const host = require('./host')
const ENV_TYPE = process.env.ENV_TYPE || 'dev'
const { APP_TYPE } = process.env
// if (APP_TYPE === 'hn') {
//     fs.copyFileSync('./config/hn/project.config.json', './project.config.json');
//     console.log('**********************************************');
//     console.log('Hainan project config was copied to root folder');
//     console.log('**********************************************');
// }

let TARO_CMD = 'build'
let TARO_ENV = 'rn'
const command = process.env.npm_lifecycle_event
if (command && command.indexOf(':') > 0) {
  TARO_CMD = command.split(':')[0]
  TARO_ENV = command.split(':')[1]
}

function getDistPath() {
  if (TARO_ENV === 'h5') {
    return process.env.ENV_TYPE === 'production' ? 'h5_prod' : `h5_${ENV_TYPE}`
  }
  return TARO_ENV
}
const DIST_PATH = getDistPath()
const HOST_URL = host[TARO_ENV][ENV_TYPE || 'dev']
const OSS_URL = host.oss[ENV_TYPE || 'dev']
const PRIVATE_OSS = host.privateOSS[ENV_TYPE || 'dev']
const CLOUD_ID = host.cloudId[ENV_TYPE || 'dev']
const DOMAIN_URL = host.domain[ENV_TYPE || 'dev']
const APP_ID = host[TARO_ENV].appId
const WEAPP_ANALYTICS_ID = host.weappAnalyticsId[ENV_TYPE || 'dev']
const H5_ANALYTICS_ID = host.h5AnalyticsId[ENV_TYPE || 'dev']

console.log('====== CONFIG =====')
console.log(`====== APP_TYPE  ----> ${APP_TYPE}`)
console.log(`====== DIST_PATH  ----> ${DIST_PATH}`)
console.log(`====== ENV_TYPE  ----> ${ENV_TYPE}`)
console.log(`====== NODE_ENV  ----> ${process.env.NODE_ENV}`)
console.log(`====== TARO_CMD    ----> ${TARO_CMD}`)
console.log(`====== TARO_ENV    ----> ${TARO_ENV}`)
console.log(`====== HOST_URL    ----> ${HOST_URL}`)
console.log(`====== OSS_URL     ----> ${OSS_URL}`)
console.log(`====== PRIVATE_OSS ----> ${PRIVATE_OSS}`)
console.log(`====== CLOUD_ID     ----> ${CLOUD_ID}`)
console.log(`====== DOMAIN_URL     ----> ${DOMAIN_URL}`)
console.log(`====== APP_ID     ----> ${APP_ID}`)
console.log(`====== WEAPP_ANALYTICS_ID     ----> ${WEAPP_ANALYTICS_ID}`)
console.log(`====== H5_ANALYTICS_ID     ----> ${H5_ANALYTICS_ID}`)
console.log('====== END CONFIG =====')

// process.env.NODE_ENV === 'production' ? host[TARO_ENV].prod : process.env.NODE_ENV === 'development' ? host[TARO_ENV].dev : host[TARO_ENV].preissue
// console.log(process.env.NODE_ENV, process.env.npm_lifecycle_event, process.env.CLIENT_ENV)
// console.log(HOST_URL

const isH5 = process.env.TARO_ENV === 'h5'

// const API_HOST = process.env.NODE_ENV === 'production' ? host[TARO_ENV].prod : process.env.NODE_ENV === 'development' ? host[TARO_ENV].test : host[TARO_ENV].preissue

// const conditionAlias = {
//   "react": path.resolve(__dirname, "../node_modules/@tarojs/taro"),
//   "axios": path.resolve(__dirname, "../node_modules/taro-axios")
//   // "axios-hooks": path.resolve(__dirname, "../node_modules/axios-hooks/es"),
// }

// if(process.env.TARO_ENV === 'h5') {
//   Object.assign(conditionAlias, {
//     'react': path.resolve(__dirname, '../node_modules/nervjs'),
//     'react-dom': path.resolve(__dirname, '../node_modules/nervjs')
//   })
// }

const deviceRatio = isH5 ? {
  375: 640 / 375,
  640: 1,
  750: 640 / 750,
  828: 640 / 828
} : {
  375: 2,
  640: 2.34 / 2,
  750: 1,
  828: 1.81 / 2
}
const config = {
  projectName: 'p8hCare',
  date: '2020-5-21',
  designWidth: 375,
  deviceRatio,
  sourceRoot: 'src',
  outputRoot: `dist/${DIST_PATH}`,
  framework: 'react', // h5放开，可移除 @tarojs/components warning
  compiler: 'webpack4',
  cache: {
    enable: false // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
  },
  performance: {
    hints: false,
    maxEntrypointSize: 5 * 1024 * 1024,
    maxAssetSize: 5000 * 1024,
  },
  babel: {
    sourceMap: true,
    presets: [
      ['env', {
        modules: false
      }]
    ],
    plugins: [
      'transform-decorators-legacy',
      'transform-class-properties',
      'transform-object-rest-spread',
      '@babel/plugin-proposal-optional-chaining',
      ['transform-runtime', {
        helpers: false,
        polyfill: false,
        regenerator: true,
        moduleName: 'babel-runtime'
      },
      '@tarojs/plugin-platform-weapp', {
        enablekeyboardAccessory: true
      }
      ]
    ]
  },
  defineConstants: {
    // TESTO: '测试常量',
    // 'TESTA': 'AAAA',
    // 'TESTB': { 'TESTB1': 'BBB1'}
    // globalVairable: {
    //   env: 'dev',
    //   // testtype: JSON.stringify('DEV'),
    // },
    // DBConfig: {
    //   BASE_URL: `${HOST_URL}`,
    //   OSS_URL:`${OSS_URL}`,
    //   APP_NAME: `'${pkg.app_name}'`,
    //   APP_VERSION: `'${pkg.version}'`
    // }
    // HOST: isH5 ? '"/mbl"' : HOST_URL,
    // BASE_URL: `${HOST_URL}`,
    // OSS_URL:`${OSS_URL}`,
    // APP_NAME: `'${pkg.app_name}'`,
    // APP_VERSION: `'${pkg.version}'`
  },
  alias: {
    // ...conditionAlias,
    '@src': path.resolve(__dirname, '..', 'src'),
    '@ASSET': path.resolve(__dirname, '..', 'src/assets'),
    '@IMG': path.resolve(__dirname, '..', 'src/assets/images'),
    '@I18N': path.resolve(__dirname, '..', 'src/i18n'),
    '@API': path.resolve(__dirname, '..', 'src/services'),
    '@CONSTANTS': path.resolve(__dirname, '..', 'src/constants'),
    '@PAGES': path.resolve(__dirname, '..', 'src/pages'),
    '@COMPONENTS': path.resolve(__dirname, '..', 'src/components'),
    '@HOOKS': path.resolve(__dirname, '..', 'src/hooks'),
    '@ACTIONS': path.resolve(__dirname, '..', 'src/redux/actions'),
    '@REDUCERS': path.resolve(__dirname, '..', 'src/redux/reducers'),
    '@SAGAS': path.resolve(__dirname, '..', 'src/redux/sagas'),
    '@REDUXITF': path.resolve(__dirname, '..', 'src/redux/interface'),
    '@STORE': path.resolve(__dirname, '..', 'src/redux/store'),
    '@SELECTORS': path.resolve(__dirname, '..', 'src/redux/selectors'),
    '@UTILS': path.resolve(__dirname, '..', 'src/utils'),
    '@HOC': path.resolve(__dirname, '..', 'src/HOC'),
    '@CONFIG': path.resolve(__dirname, '..', 'src/config'),
    '@NAVIGATION': path.resolve(__dirname, '..', 'src/navigation'),
    '@SUBPACKAGES': path.resolve(__dirname, '..', 'src/subpackages'),
    '@STYLE': path.resolve(__dirname, '..', 'src/style'),
    '@INTERFACES': path.resolve(__dirname, '..', 'src/interfaces'),
    '@/package': '../package.json',
    '@/project': '../project.config.json'
    // "@/readme": "../README.md",
  },
  mini: {
    webpackChain(chain) {
      chain.optimization.minimize(true)
      chain.plugin('terser').use(TerserPlugin, [
        {
          extractComments: false,
          terserOptions: {
            output: {
              comments: false
            }
          }
        }
      ])

      // bundle 分析
      // chain.plugin('analyzer')
      //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, [])
    // },
    },
    optimizeMainPackage: {
      enable: true
    },
    postcss: {
      autoprefixer: {
        enable: true,
        config: {
        }
      },
      pxtransform: {
        enable: true,
        config: {

        }
      },
      url: {
        enable: true,
        config: {
          limit: 10240 // 设定转换尺寸上限
        }
      },
      cssModules: {
        enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: 'module', // 转换模式，取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    },
    miniCssExtractPluginOption: {
      ignoreOrder: true
    }
  },
  rn: {
    postcss: {
      cssModules: {
        enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: 'module', // 转换模式，取值为 global/module
        }
      }
    },
  },
  h5: {
    publicPath: '/',
    staticDirectory: 'static',
    router: { mode: 'browser' },
    devServer: {
      proxy: {
        '/wmp/': {
          target: HOST_URL,
          changeOrigin: true,
        },
        '/ossUpload': {
          target: OSS_URL,
          changeOrigin: true,
          pathRewrite: { '^/ossUpload': '' },
        },
        '/ossUploadPrivate': {
          target: `https://${PRIVATE_OSS}.oss-cn-hangzhou.aliyuncs.com`,
          changeOrigin: true,
          pathRewrite: { '^/ossUploadPrivate': '' },
        },
      }
    },
    postcss: {
      cssModules: {
        enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
        config: {
          namingPattern: 'module', // 转换模式，取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]'
        }
      }
    },
    miniCssExtractPluginOption: {
      ignoreOrder: true,
      // chunkFilename: './css/[chunkhash:4].css'
    },
  }
}

// eslint-disable-next-line func-names
module.exports = function (merge) {
  console.log('CONFIG,NODE_ENV', process.env.NODE_ENV)
  if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
    return merge({}, config, require('./dev'))
  }
  return merge({}, config, require('./prod'))
}
